from fastapi import APIRouter, Query,UploadFile
from pandas.plotting import table
from tortoise.expressions import Q

from app.core.ctx import CTX_USER_ID
from app.core.dependency import DependCustomerAuth
from app.models.admin import User
from app.controllers.appointment.space import appointment_space_controller
from app.controllers.saas.performance_percentage import performance_percentage_controller
from app.controllers.system.user import user_controller
from app.models import Goods, CustomerUser
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.saas import *
from app.settings.config import settings
from datetime import datetime, timedelta
import calendar

saas_performance_percentage_router = APIRouter()
model_name = "提成记录"


@saas_performance_percentage_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_settings_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"员工名称"),
        start_time: str = Query(None, description=f"开始时间"),
):
    q = Q()
    user_id = CTX_USER_ID.get()
    user = await user_controller.get(user_id)
    if user.space_id:
        q &= Q(space_id__in=user.space_id)
    if name:
        search_users = await User.filter(alias__contains=name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
        q &= Q(user_id__in=search_user_ids)
    if start_time:
        dt = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S')
        # 获取当月最后一天的日期
        _, last_day = calendar.monthrange(dt.year, dt.month)
        end_time = datetime(dt.year, dt.month, last_day, 23, 59, 59)
        q &= Q(created_at__range=[start_time, end_time])
    space_objs = await appointment_space_controller.level_list()

    total, data = await performance_percentage_controller.do_list(page=page, page_size=page_size, search=q)
    for item in data:
        goods_data = await Goods.filter(id=item['goods_id']).first().values()
        customer_data = await CustomerUser.filter(id=item['customer_id']).first().values()
        user_data = await User.filter(id=item['user_id']).first().values()
        item['project_name'] = goods_data['name']
        item['receive_name'] = customer_data['name']
        item['space_name'] = space_objs[item['space_id']]
        item['user_name'] = user_data["alias"]
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@saas_performance_percentage_router.get("/get", summary=f"查看{model_name}")
async def do_settings_get(
        data_id: int = Query(..., description="ID"),
):
    data = await performance_percentage_controller.do_detail(data_id=data_id)
    return Success(data=data)

@saas_performance_percentage_router.post("/create", summary=f"创建{model_name}")
async def do_settings_create(
        data_in: PerformancePercentageCreate,
):
    await performance_percentage_controller.do_create(obj_in=data_in)
    return Success(msg="创建成功")

@saas_performance_percentage_router.post("/update", summary=f"更新{model_name}")
async def do_settings_update(
        data_in: PerformancePercentageUpdate,
):
    await performance_percentage_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@saas_performance_percentage_router.delete("/delete", summary=f"删除{model_name}")
async def do_settings_delete(
        data_id: int = Query(..., description="ID"),
):
    await performance_percentage_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")

